package com.lhh.company.website.admin;

import com.lhh.company.website.config.SysUserDetails;
import com.lhh.company.website.entity.Res;
import com.lhh.company.website.entity.SysUser;
import jakarta.servlet.http.HttpSession;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Log4j2
@RestController
public class AuthApi {

    @Autowired
    AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public Res<String> login(@RequestBody SysUser sysUser, HttpSession httpSession) {
        //未认证令牌，参考UsernamePasswordAuthenticationFilter这个来写就行了

        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(sysUser.getName(), sysUser.getPasswd());

        Authentication auth = authenticationManager.authenticate(authRequest);

        //这里还有一点要注意，我们一般都是从SecurityContextHolder取到用户信息的，那这里也别忘了给他放进去
        SecurityContextHolder.getContext().setAuthentication(auth);
            //还有一点要注意，新版的Security是从session中获取的，那本次会话的下次请求想要拿到，也需要丢到session中去
        httpSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,SecurityContextHolder.getContext());
        SysUserDetails sysUserDetails = (SysUserDetails) auth.getPrincipal();
        sysUserDetails.setPassword(null);
        return Res.succ(auth,"登录成功");
    }


    @RequestMapping("/logout")
    public Res<String> logout( HttpSession httpSession) {
        SecurityContextHolder.getContext().setAuthentication(null);
        httpSession.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return Res.succMsg("注销成功");
    }
}
